﻿using DtuService;
using NetCommand;
using SuperSocket.SocketBase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;

namespace DtuService
{
    class TCPServer : IServer
    {
        private object lock_obj = new object();
        public TcpService ServerApp;
        
        /// <summary>
        /// 开启 监听
        /// </summary>
        public void StartServer()
        {
            Console.WriteLine("...开始TCP监听");
            int port = 8100;
            ServerApp = new TcpService();
            int.TryParse(ServerMain.Instance.Config.AppSettings.Settings["tcpPort"].Value, out port);
            int parallelNum = 0;
            int.TryParse(ServerMain.Instance.Config.AppSettings.Settings["ParallelNum"].Value, out parallelNum);
            int socketTimeOutMS = 0;
            int.TryParse(ServerMain.Instance.Config.AppSettings.Settings["SocketTimeOutMS"].Value, out socketTimeOutMS);
            if (!ServerApp.Setup(port))
            {
                Debug.Log("端口设置失败");
                return;
            }
            
            ServerApp.NewRequestReceived += ServerApp_NewRequestReceived;
            ServerApp.NewSessionConnected += ServerApp_NewSessionConnected;
            //启动服务  
            if (!ServerApp.Start())
            {
                Console.WriteLine("启动服务失败!");
                Console.ReadKey();
                return;
            }
            Debug.LogDebug("Start listen socket 0.0.0.0:" + port + " success");
           
            NetCommand.NetCommandFactory.RegistCommand();
            NetCommand.CommandTranslator.Instance.CHECK_CMD_FRONT_CODE = NetCommand.NetCommon.C2S_HEADER_CODE;
        }

        //序列化
        public static byte[] Serialize(object obj)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            bf.Serialize(stream, obj);
            byte[] datas = stream.ToArray();
            stream.Dispose();
            return datas;
        }
        //反序列化
        public static object Deserialize(byte[] datas)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(datas, 0, datas.Length);
            object obj = bf.Deserialize(stream);
            stream.Dispose();
            return obj;
        }
        private void ServerApp_NewSessionConnected(ByteSession session)
        {
            Debug.LogDebug("TCP 连接 IP：" + session.IPAddress);
        }

        private void ServerApp_NewRequestReceived(ByteSession session, SuperSocket.SocketBase.Protocol.BinaryRequestInfo requestInfo)
        {
            if (int.Parse(requestInfo.Key) == NetCommon.D2S_TICK_CODE)
            { // 心跳
                session.SendMessage(new byte[] { (byte)NetCommon.D2S_TICK_CODE });
                Console.Write("F5 ");
                return;
            }
            Debug.LogDebug("TCP 收到消息： " + EncodingTools.outPut16Number(requestInfo.Body, requestInfo.Body.Length));
            ServerMain.GetServer<MessageServer>().InsertMessage(session, requestInfo.Body);
        }
        
        public void Init()
        {
            StartServer();
        }

        public void Tick(float deltaTime)
        {
            
        }

        public void ShutDown()
        {
             
        }
    }
}
